package com.changgou.search.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import search.pojo.SkuInfo;

import java.util.List;
import java.util.Map;
@Service
@Repository
public class ESManagerServiceImpl implements ESManagerService {
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private SkuFeign skuFeign;

    //创建索引库
    @Override
    public void createMappingAndIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }
//导入全部sku集合进入到索引库
    @Override
    public void importAll() {

        //查询sku集合
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
if (skuList==null||skuList.size()<=0){
    throw new RuntimeException("当前没有数据被查询到，无法导入索引库");
}
        //skuList转换为Json
        String jsonSkuList = JSON.toJSONString(skuList);
        //将json转换为skuInfo
        List<SkuInfo> skuInfos = JSON.parseArray(jsonSkuList, SkuInfo.class);
        for (SkuInfo skuInfo:skuInfos){
            //将规格信息转换为Map
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }

        //导入数据库
        esManagerMapper.saveAll(skuInfos);
    }
//根据spuID查询skulist，添加到索引库
    @Override
    public void importDataToESBySpuId(String spuId) {
        List<Sku> skuListBySpuId = skuFeign.findSkuListBySpuId(spuId);
        if (skuListBySpuId==null||skuListBySpuId.size()<=0){
            throw new RuntimeException("当前没有数据被查询到，无法导入索引库");
        }
        String jsonSkuList= JSON.toJSONString(skuListBySpuId);
        List<SkuInfo> skuInfos = JSON.parseArray(jsonSkuList, SkuInfo.class);
        for (SkuInfo skuInfo:skuInfos){
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void delDataBySpuId(String spuId) {
        List<Sku> skuListBySpuId = skuFeign.findSkuListBySpuId(spuId);
        if (skuListBySpuId==null||skuListBySpuId.size()<=0){
            throw new RuntimeException("当前没有数据被查询到，无法导入索引库");
        }
        for (Sku sku:skuListBySpuId){
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
